﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.ChangeHouse
{
    public class QueryChangeHouseHandler : IRequestHandler<QueryChangeHouseCommand, Result<PageResultDto<ChangeHouseDto>>>
    {

        /// <summary>
        /// 猪只转舍仓储
        /// </summary>
        private readonly IBaseRepository<ChangeHouses> changeHouseRepository;
        /// <summary>
        /// 基本信息耳号仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 转舍信息仓储
        /// </summary>
        private readonly IBaseRepository<ChangeHouseTypes> changeHouseTypesRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsRepository;
        /// <summary>
        /// 品种
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="changeHouseRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="changeHouseTypesRepository"></param>
        /// <param name="bedroomTypesRepository"></param>
        /// <param name="varietiesRepository"></param>
        public QueryChangeHouseHandler(IBaseRepository<ChangeHouses> changeHouseRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<ChangeHouseTypes> changeHouseTypesRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldsRepository, IBaseRepository<Varieties> varietiesRepository)
        {
            this.changeHouseRepository = changeHouseRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.changeHouseTypesRepository = changeHouseTypesRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldsRepository = fieldsRepository;
            this.varietiesRepository = varietiesRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<ChangeHouseDto>>> Handle(QueryChangeHouseCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<ChangeHouseDto>>() { Code = (int)CommonErrorCode.Search, Data = new PageResultDto<ChangeHouseDto>() };
            var page = new PageResultDto<ChangeHouseDto>() { TotalCount = 0, PageCount = 0, List = new List<ChangeHouseDto>() };
            try
            {
                var list = await(from a in await changeHouseRepository.GetAll()
                                 join b in await basicInformationRepository.GetAll()
                                 on a.BasicInforId equals b.BasicInforId
                                 join c in await bedroomsRepository.GetAll()
                                 on a.BedroomId equals c.BedroomId
                                 join d in await changeHouseTypesRepository.GetAll()
                                 on a.ChangeHouseTypeId equals d.ChangeHouseTypeId
                                 join g in await fieldsRepository.GetAll()
                                 on a.FieldId equals g.FieldId
                                 select new ChangeHouseDto()
                                 {
                                     ChangeHouseId = a.ChangeHouseId,
                                     BasicInforId = a.BasicInforId,
                                     ChangeHouseDate = a.ChangeHouseDate,
                                     ChangeHouseTypeId = a.ChangeHouseTypeId,
                                     BedroomId = a.BedroomId,
                                     FieldId = a.FieldId,
                                     TurnBuilding = a.TurnBuilding,
                                     TurnColumn = a.TurnColumn,
                                     VarietyName = a.VarietyName,
                                     Gender = b.Gender,
                                     IsChangeHouse = a.IsChangeHouse,
                                     EarNumber = b.EarNumber,
                                     BedroomName = c.BedroomName,
                                     ChangeHouseTypeName = d.ChangeHouseTypeName,
                                     FieldName = g.FieldName,
                                     CreatedOwner = a.CreatedOwner,
                                     CreatedTime = a.CreatedTime,
                                     UpdateOwner = a.UpdateOwner,
                                     UpdateTime = a.UpdateTime,
                                     ExamineOwner = a.ExamineOwner,
                                     ExamineTime = a.ExamineTime,
                                 }).ToListAsync();
                //耳号查询
                if (request.BasicInforId != 0)
                {
                    list = list.Where(d => d.BasicInforId == request.BasicInforId).ToList();
                }
                //转舍查询
                if (request.ChangeHouseTypeId != 0)
                {
                    list = list.Where(d => d.ChangeHouseTypeId == request.ChangeHouseTypeId).ToList();
                }
                //转入栋舍查询
                if (!string.IsNullOrEmpty(request.TurnBuilding))
                {
                    list = list.Where(d => d.TurnBuilding.Contains(request.TurnBuilding)).ToList();
                }
                //转入栏位查询
                if (!string.IsNullOrEmpty(request.TurnColumn))
                {
                    list = list.Where(d => d.TurnColumn.Contains(request.TurnColumn)).ToList();
                }
                //转出栋舍查询
                if (request.BedroomId != 0)
                {
                    list = list.Where(d => d.BedroomId == request.BedroomId).ToList();
                }
                //转出栏位查询
                if (request.FieldId != 0)
                {
                    list = list.Where(d => d.FieldId==request.FieldId).ToList();
                }
               
                //总条数
                page.TotalCount = list.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.pageSize);
                page.List = list.OrderBy(d => d.ChangeHouseId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = page;
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "猪只转舍列表显示成功";
            }
            catch (Exception)
            {
                result.Msg = "猪只转舍列表显示异常";
            }
            return result;
        }
    }
}
